package com.teamide.util;

import java.io.File;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

public class RequestUtil {

	public static final String getServerUrl(HttpServletRequest request) {
		String contextPath = getContextPath(request);
		String requestURL = getRequestURL(request);
		return getServerUrl(contextPath, requestURL);
	}

	public static final String getServerUrl(String contextPath, String requestURL) {
		int index = requestURL.indexOf("://");
		if (index >= 0) {
			index = index + 3;
		} else {
			index = 0;
		}
		String url = requestURL;
		if (StringUtil.isEmpty(contextPath)) {
			contextPath = "/";
		}
		if (!contextPath.startsWith("/")) {
			contextPath = "/" + contextPath;
		}
		int i = requestURL.indexOf(contextPath, index);
		if (i > 0) {
			url = requestURL.substring(0, i + contextPath.length());
		}
		if (url.endsWith("/")) {
			url = url.substring(0, url.length() - 1);
		}

		return url;
	}

	public static final File getServerFolder(HttpServletRequest request) {

		return getServerFolder(request.getServletContext());
	}

	public static final File getServerFolder(ServletContext context) {

		String serverPath = context.getRealPath("");
		return new File(serverPath);
	}

	public static String getServletpath(HttpServletRequest request) {

		String servletpath = request.getServletPath();
		String pathinfo = request.getPathInfo();
		if (!StringUtil.isEmpty(pathinfo)) {
			servletpath = servletpath + "/" + pathinfo;
		}
		if (StringUtil.isEmpty(servletpath)) {
			return "/";
		}

		return trimServletpath(servletpath);
	}

	public static String trimServletpath(String servletpath) {

		if (StringUtil.isEmpty(servletpath)) {
			return "/";
		}
		servletpath = servletpath.replaceAll("/+", "/");
		if (servletpath.length() > 2) {
			if (servletpath.lastIndexOf("/") == servletpath.length() - 1) {
				servletpath = servletpath.substring(0, servletpath.length() - 1);
			}
		}
		return servletpath;
	}

	public static String getContextPathURL(HttpServletRequest request, String path) {

		if (StringUtil.isEmpty(path)) {
			path = "";
		}
		if (path.startsWith("http") || path.startsWith("//")) {
			return path;
		}

		String contextPath = request.getContextPath();
		if (StringUtil.isEmpty(contextPath)) {
			contextPath = "/";
		}
		if (!contextPath.endsWith("/")) {
			contextPath += "/";
		}
		if (path.startsWith("/")) {
			path = path.substring(1);
		}
		return contextPath + path;

	}

	public static byte[] getBytesBody(HttpServletRequest request) throws Exception {
		try {

			return IOUtil.read(request.getInputStream());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getBody(HttpServletRequest request) {
		try {

			byte[] bytes = getBytesBody(request);
			if (bytes != null) {
				return new String(bytes);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将request转成Map
	 * 
	 * @param request
	 *            HTTP请求对象
	 * @return 返回参数键值对
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> getRequestMap(HttpServletRequest request) {

		Map<String, String> requestmap = new HashMap<String, String>();
		if (request.getAttribute("URL_DATA") != null) {
			requestmap = (Map<String, String>) request.getAttribute("URL_DATA");
		}
		Map<String, String[]> map = request.getParameterMap();
		for (String key : map.keySet()) {
			if (map.get(key) != null) {
				if (map.get(key)[0] != null) {
					String value = map.get(key)[0];
					requestmap.put(key, value);

				}
			}
		}
		return requestmap;
	}

	public static Map<String, String> getRequestHeader(HttpServletRequest request) {

		Map<String, String> header = new HashMap<String, String>();
		Enumeration<String> names = request.getHeaderNames();
		if (names != null) {
			while (names.hasMoreElements()) {
				String name = names.nextElement();
				header.put(name, request.getHeader(name));
			}
		}
		return header;
	}

	public static String getIP(HttpServletRequest request) {

		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {
			ip = request.getRemoteAddr();
		} else {
			ip = request.getHeader("x-forwarded-for");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.indexOf(",") != -1) {
			ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		}
		return ip;
	}

	public static String getRequestURL(HttpServletRequest request) {

		return request.getRequestURL().toString();
	}

	public static String getContextPath(HttpServletRequest request) {

		return request.getContextPath();
	}

}
